import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { Form } from '@ant-design/compatible';
import { addTab } from '@/utils/utils';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Input,
  Button,
  Table,
  Divider,
  Popconfirm,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { pathname } = window.location;
const { Item } = Form;


interface BrokenListProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: any;
  INITINFO: any;
  screen: string;
}

interface BrokenListState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  rowId: number;
}

@connect(({
  deputyList: { dataInfo },
  common: { INITINFO },
}: any) => ({
  dataInfo,
  INITINFO,
}))

class BrokenListElem extends Component<BrokenListProps, BrokenListState> {
  columns = [
    { title: '编号', dataIndex: 'code' },
    { title: '名称', dataIndex: 'name' },
    {
      title: '操作',
      dataIndex: 'id',
      render: (id: number, record: any) => (
        <>
          <span
            className="operLink"
            onClick={() => this.handleEdit(id, record.name)}
          >
            编辑
          </span>
          <Divider type="vertical" />
          <Popconfirm
            title="确定要删除当前副柜吗？"
            onConfirm={() => this.handleDel(id)}
            className="operLink"
            okText="确定"
            cancelText="取消"
          >
            删除
          </Popconfirm>
        </>
      ),
    },
  ]

  state: BrokenListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query }, screen } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  };

  fetchDataValues = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'deputyList/fetch',
      payload: this.getQueryParams(),
    });
  }

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, fieldsValue) => {
      if (errors) return;

      const query = { pageIndex: 1, ...fieldsValue };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '副柜管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '副柜管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '副柜管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  handleAdd = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '添加副柜',
      url: '/basic/deputyCabinetManagement/list/add',
    });
  }

  handleEdit = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/basic/deputyCabinetManagement/list/edit?id=${id}`,
    });
  }

  handleDel = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'deputyList/delete',
      payload: {
        params: { id },
        query: this.getQueryParams(),
      },
    });
  }

  render() {
    const {
      pageIndex, pageSize,
    } = this.state;

    const {
      dataInfo,
      form: { getFieldDecorator },
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="副柜名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handleAdd}
            >
              新建副柜
            </Button>
          </div>

          <Table
            rowKey="id"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<BrokenListProps>()(BrokenListElem);
